package home.study.xxy.bs.security;

import home.study.xxy.bs.fifter.JwtAuthTokenFilter;
import home.study.xxy.bs.handler.AccessFailImpl;
import home.study.xxy.bs.handler.AuthenFailImpl;
import home.study.xxy.bs.service.impl.LoginServiceImpl;
import home.study.xxy.bs.service.impl.UserserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.sql.DataSource;

/**
 * @author xiaoxiangyu
 * @create 2022-05-17 15:06
 * @功能：
 */
@EnableWebSecurity
public class JobSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthTokenFilter jwtAuthTokenFilter;

    @Autowired
    private AccessFailImpl accessFail;

    @Autowired
    private AuthenFailImpl authenFail;

    @Autowired
    private UserserDetailServiceImpl userserDetailService;
//    @Bean
//    public UserNamePwdFilter testFilter() {
//        UserNamePwdFilter testFilter = new UserNamePwdFilter();
//        testFilter.setFilterProcessesUrl("/sss");
//        testFilter.setUsernameParameter("userName");
//        testFilter.setPasswordParameter("pwd");
//        try {
//            testFilter.setAuthenticationManager(authenticationManagerBean());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        testFilter.setAuthenticationSuccessHandler(loginSuccessHandler);
//        testFilter.setAuthenticationSuccessHandler((req,resp,ex) ->{
//            HashMap<String, Object> map = new HashMap<>();
//            map.put("msg","登录成功");
//            resp.setStatus(200);
//            resp.getWriter().println(new ObjectMapper().writeValueAsString(resp));
//        });

//        return testFilter;
//    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }




//    @Override
//    @Bean
//    protected UserDetailsService userDetailsService() {
//        //内存虚拟账号测试
////        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
////        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("e10adc3949ba59abbe56e057f20f883e").roles("admin").build());
//
//
//
//        //根据登录信息进行认证
//        //1、查询用户
//        //2、获取角色信息
////        loginMapper.getLoginData();
//
//        JdbcUserDetailsManager jdbc = new JdbcUserDetailsManager();
//        UserDetails xxy = jdbc.loadUserByUsername("xxy");
//        System.out.println(xxy.getUsername() + "   ===   "  + xxy.getPassword());
////
////        jdbc.createUser();
//
//
//        return jdbc;
//    }

    /**
     *  配置权限访问
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                //关闭 csrf
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/login").anonymous()
                .and()
                .authorizeRequests()
                .antMatchers("/checkImage").anonymous()
                .and()
                .authorizeRequests()
                .antMatchers("/addUser").anonymous()
                .antMatchers("/jobController/queryJobById").hasAuthority("ROLE_user")
                //除了上边以外请求都会认证
                .anyRequest().authenticated();

        //自定义 token认证信息处理
        http
                .addFilterAfter(jwtAuthTokenFilter, UsernamePasswordAuthenticationFilter.class);


        //添加认证和授权失败响应
        http
                .exceptionHandling()
                .accessDeniedHandler(accessFail)
                .authenticationEntryPoint(authenFail);

        //spring security 跨域
        http
                .cors();



//        .hasRole("admin")
//        http.authorizeRequests()
////                .anyRequest().permitAll()
////                .antMatchers("/login").permitAll()
//                .antMatchers("/test").hasRole("admin")
//                .and()
//                .csrf().disable();
//                .antMatchers("/addUser").permitAll()
//                .antMatchers("/checkImage").permitAll()
//                .antMatchers("/otherController").permitAll()
//                .antMatchers("/jobController/**").permitAll()
//                .and()
//                .formLogin().loginPage("/login")
//                .successHandler(loginSuccessHandler);;
//                .antMatchers("/login/**").permitAll()
//                .antMatchers("/otherController/**").permitAll()
//                .antMatchers("/jobController/**").hasRole("root")
//            .and()
//                .formLogin().loginPage("/login")
//                .loginProcessingUrl("/login")
//                .usernameParameter("userName")
//                .passwordParameter("pwd")
//                .defaultSuccessUrl("/index").permitAll()
//                .successHandler(loginSuccessHandler);
//                .failureUrl("login/error");
//
//        http.formLogin().failureForwardUrl("");
//        http.formLogin().successForwardUrl("");
//
//
//        更换自定义过滤器
//        http.addFilterAt(testFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userserDetailService).passwordEncoder(passwordEncoder());
//        auth.userDetailsService(userDetailsService());
//        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
//        auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder())
//                .usersByUsernameQuery("select id,user_name,pwd from user where user_name = ?")
//                .authoritiesByUsernameQuery("select username, role from user_roles where user_id = ?")
//                ;
    }
//    /**
//     * 加载用户数据类
//     */
//    public UserDetailsService userDetailService(){
//        @Autowired
//        UserDetailServiceImpl userDetailService;
//        return userDetailService;
//    }

    /**
     * 自定义密码加密类
     */
    @Bean
    public PasswordEncoder passwordEncoder(){

        return new MD5PasswordEncoder();
    }
}
